<template>
  <el-dialog :visible.sync="dialogVisible" title="新增上架商品" width="1200px" :close-on-click-modal="false" v-drag2anywhere>
    <div class="title">基本信息</div>
    <el-form :model="formData" label-width="120px" :rules="rules" size="mini" ref="formData">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="上架渠道:" prop="platform">
            <el-select v-model="formData.platform" @change="handlePlatformChange" style="width: 100%;">
              <el-option label="京东自营" value="京东自营"></el-option>
              <el-option label="京东慧采" value="京东慧采"></el-option>
              <el-option label="政采云" value="政采云"></el-option>
              <el-option label="军网" value="军网"></el-option>

            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <el-form-item label="申请商品名称:" prop="pretitle">
            <el-input v-model="formData.pretitle" placeholder="申请上架商品的标题"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-row>
            <el-col :span="12">
              <el-form-item label="品牌:" prop="brand">
                <el-input v-model="formData.brand" placeholder="请输入品牌"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规格型号:" prop="brand">
                <el-input v-model="formData.model" placeholder="规格型号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计量单位:" prop="unit">
                <el-input v-model="formData.unit" placeholder="计量单位"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="最小起订量:" prop="mmq">
                <el-input-number v-model="formData.mmq" placeholder="起订量" style="width: 100%;"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细参数:">
            <el-input type="textarea" :rows="4" placeholder="商品详细参数" v-model="formData.params" maxlength="500"
              show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="上架单价:" prop="price">
            <el-input-number v-model="formData.price" :precision="2" style="width: 100%;">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="需求数量:" prop="num">
            <el-input-number v-model="formData.num" placeholder="需求数量" style="width: 100%;">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="质保期:" prop="exptime">
            <el-input v-model="formData.exptime" placeholder="产品质保期"></el-input>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="销售区域:" prop="allregion">
            <el-radio-group v-model="formData.allregion">
              <el-radio label="1">全国地区</el-radio>
              <el-radio label="0">部分地区</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="14" v-if="formData.allregion=='0'">
          <el-form-item label="指定区域:">
            <el-input v-model="formData.region"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="参考链接:">
            <el-input v-model="formData.cklink" placeholder="如果JD自营店有此产品在售,请填写在售产品链接地址!"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col >
          <el-form-item label="备注信息:">
            <el-input v-model="formData.memo" type="textarea" rows="3" placeholder="备注信息"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="title">产品图片</div>
          <div style="color: rgb(153, 153, 153); font-size: 12px; margin-left: 5px; margin-bottom: 20px;">
            上传图片至少上传三张!</div>
          <div style="margin-bottom: 20px;">
            <el-upload list-type="picture-card" ref="thumbupload" :file-list="thumbuploadConfig.imgList"
              :action="thumbuploadConfig.action" :headers="thumbuploadConfig.headers" :accept="thumbuploadConfig.accept"
              :limit="thumbuploadConfig.limit" :on-change="handleThumbChange" :auto-upload="false"
              :on-remove="handleThumbRemove" :on-exceed="handleThumbLimit" multiple
              :before-remove="handleThumbBeforRemove" :on-preview="handleThumbPreviewPreview">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog title="图片预览" :visible="previewImg" append-to-body style="text-align: center;"
              @close="previewImg=false">
              <img :src="previewUrl" />
            </el-dialog>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="title">产品资质文件</div>
          <div style="color: rgb(153, 153, 153); font-size: 12px; margin-left: 5px; margin-bottom: 20px;">
            请上传产品线所需资质文件，例如：商标注册证、CCC证书、厂家授权、检测报告等</div>
          <el-upload list-type="picture-card" ref="zzupload" :file-list="zzuploadConfig.imgList"
            :action="zzuploadConfig.action" :headers="zzuploadConfig.headers" :accept="zzuploadConfig.accept"
            :limit="zzuploadConfig.limit" :on-change="handleZZChange" :auto-upload="false" :on-remove="handleZZRemove"
            :on-exceed="handleZZLimit" multiple :before-remove="handleZZBeforRemove"
            :on-preview="handleZZPreviewPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-col>
      </el-row>
      <PDFViewer v-if="pdfVisible" ref="pdfUI"></PDFViewer>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
      <el-button type="primary" size="medium" @click="handleSave">提交申请</el-button>
    </div>
  </el-dialog>
</template>

<script>
  export default {
    data() {
      var validateSize = (rule, value, callback) => {
        if (value.x == 0 || value.y == 0 || value.z == 0) {
          callback(new Error("长宽高任意项都不能为0"));
        } else {
          callback();
        }
      };
      var validateweight = (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error("重量不能等于0KG!"));
        } else {
          callback();
        }
      };
      var validateprice = (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error("单价不能为0!"));
        } else {
          callback();
        }
      };
      return {
        formData: {
          client: '',
          pretitle: '',
          brand: '',
          model: '',
          params: '',
          platformid: -1,
          platform: '',
          supid: -1,
          supname: '',
          mmq: 1,
          unit: '',
          num: 1,
          price: 0.00,
          alregion: "1",
          region: '',
          cklink: '',
          memo: '',
          supinfo: ''
        },
        platforms: [],
        suppliers: [],
        userinfo: JSON.parse(localStorage.getItem("userinfo")),
        //文件上传相关变量
        thumbuploadConfig: { //产品图片上传
          //文件上传相关参数
          accept: '.jpg,.jpeg,.png',
          limit: 6,
          headers: {
            token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
          },
          imgList: [],
          fileList: [],
          removeids: [], //要删除的id
          action: ""
        },
        //文件上传相关变量
        zzuploadConfig: { //产品图片上传
          //文件上传相关参数
          accept: '.pdf,.jpg,.jpeg,.png',
          limit: 10,
          headers: {
            token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
          },
          imgList: [],
          fileList: [],
          removeids: [], //要删除的id
          action: ""
        },

        rules: {
          platform: [{
            required: true,
            message: "请选择上架渠道不能空",
            trigger: "blur"
          }],
          pretitle: [{
            required: true,
            message: "申请上架名称不能为空",
            trigger: "blur"
          }],
          client: [{
            required: true,
            message: "客户名称不能为空",
            trigger: "blur"
          }],
          price: [{
            required: true,
            message: "商家价格不能为空或<0",
            trigger: "blur"
          }, {
            validator: validateprice,
            trigger: 'blur'
          }],
          supname: [{
            required: true,
            message: "请选择申请供应商!",
            trigger: "blur"
          }],
          num: [{
            required: true,
            message: "上架数量不能为空",
            trigger: "blur"
          }],
          unit: [{
            required: true,
            message: "计量单位不能为空",
            trigger: "blur"
          }],
          mmq: [{
            required: true,
            message: "最小起订量不能小于1",
            trigger: "change"
          }],
          size: [{
            required: false,
            message: "请按要求填写商品长宽高！",
            trigger: "blur"
          }, {
            validator: validateSize,
            trigger: 'blur'
          }],
          weight: [{
            required: true,
            message: "物品重量不能为空",
            trigger: "blur"
          }, {
            validator: validateweight,
            trigger: 'blur'
          }],
          allregion: [{
            required: true,
            message: "销售地区不能为空!",
            trigger: "blur"
          }]
        },
        types: [{
            label: "京东自营",
          },
          {
            label: "京东慧采",
          },
          {
            label: "政采云",
          }
        ],
        dialogVisible: true,
        pdfVisible: false,
        previewImg: false,
        previewUrl: '',
      }
    },
    mounted() {
         },
    methods: {
      querySearchAsync(str, cb) {
        this.axios.post("api/admin/clientuser/filter", {
          username: str
        }).then(res => {
          if (res.data.code) {
            cb(res.data.data);
          }
        })
      },
      init: function() {
        this.$refs.formData.resetFields(),
          this.formData = {
            client: '',
            pretitle: '',
            brand: '',
            model: '',
            params: '',
            platformid: '-1',
            platform: '',
            mmq: 1,
            unit: '',
            exptime: '',
            supid: -1,
            supname: '',
            num: 1,
            price: 0.00,
            allregion:"1",
            region: '',
            cklink: '',
            memo: '',
         };
        this.thumbuploadConfig.fileList = [];
        this.$refs.thumbupload.clearFiles();
        this.zzuploadConfig.fileList = [];
        this.$refs.zzupload.clearFiles();
      },
      handlePlatformChange: function(platform) {
        var option = this.platforms.filter(function(cur, index, a) {
          if (cur.label == platform) {
            return cur;
          }
        })[0];
        this.formData.platformid = option.id;
        this.formData.platform = option.label;
      },
      //产品图片上传处理
      handleThumbChange: function(file, list) {
        //判断文件格式和数量
        var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
        var extarr = ['jpg', 'jpeg', 'png'];
        var sizeok = file.size / 1024 / 1024 < 10;
        if (extarr.lastIndexOf(ext) == -1) {
          this.$message.error("上传文件格式必须为" + extarr.join(","));
          //删除刚上传的文件
          this.thumbuploadConfig.fileList.splice(this.thumbuploadConfig.fileList.length - 1, 1);
          return;
        }
        if (!sizeok) {
          this.$message.error("上传文件大小最大不超过2M");
          this.thumbuploadConfig.fileList.splice(this.thumbuploadConfig.fileList.length - 1, 1);
          return;
        }
        this.thumbuploadConfig.fileList = list;
      },
      handleThumbRemove: function(file) {
        if (file.id) { //如果存储 id即为已经上传好的图片
          console.log('删除了已经上传好的图片');
          this.thumbuploadConfig.rids.push(file.id);
        }
        this.thumbuploadConfig.fileList = fileList;
      },
      handleThumbBeforRemove: function() {
        return this.$confirm("此操作将会删除当前图片，是否继续?", "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      },
      handleThumbLimit: function() {
        this.$message.warning("最多可上传" + this.thumbuploadConfig.limit + "个文件");

      },
      handleThumbPreviewPreview: function() {
        alert("预览");
      },
      /***资质附件**/
      handleZZChange: function(file, list) {
        //判断文件格式和数量
        var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
        var extarr = ['jpg', 'jpeg', 'png', "doc", "docx", "xls", "xlsx", "pdf"];
        var sizeok = file.size / 1024 / 1024 < 10;
        if (extarr.lastIndexOf(ext) == -1) {
          this.$message.error("上传文件格式必须为" + extarr.join(","));
          //删除刚上传的文件
          this.zzuploadConfig.fileList.splice(this.zzuploadConfig.fileList.length - 1, 1);
          return;
        }
        if (!sizeok) {
          this.$message.error("上传文件大小最大不超过2M");
          this.zzuploadConfig.fileList.splice(this.zzuploadConfig.fileList.length - 1, 1);
          return;
        }
        this.zzuploadConfig.fileList = list;
      },
      handleZZBeforRemove: function(file, FileList) {
        return this.$confirm("此操作将会删除当前图片，是否继续?", "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      },
      handleZZRemove: function(file) {
        if (file.id) { //如果存储 id即为已经上传好的图片
          console.log('删除了已经上传好的图片');
          this.zzuploadConfig.removeids.push(file.id);
        }
      },
      handleZZLimit: function() {
        this.$message.warning("最多可上传" + this.zzuploadConfig.limit + "个文件");

      },
      handleZZPreviewPreview: function(file) {
        //预览pdf文件
        console.log(file);
        this.pdfVisible = true;
        this.$nextTick(() => {
          this.$refs.pdfUI.dialogVisible = true;
          this.$refs.pdfUI.initData(file);
        })
      },
      handleSupChange: function(sup) {
        var option = this.suppliers.filter(function(cur, index, a) {
          if (cur.name == sup) {
            return cur;
          }
        })[0];
        this.formData.supid = option.id;
        this.formData.supname = option.name;
      },
      handleSave: function() {
        this.$refs["formData"].validate(ok => {
          if (ok) {
            //检测
            let fd = new FormData();
            fd.append("platform", this.formData.platform);
            fd.append("client", this.formData.client);
            fd.append("pretitle", this.formData.pretitle);
            fd.append("platformid", this.formData.platformid);
            fd.append("platform", this.formData.platform);
            fd.append("brand", this.formData.brand);
            fd.append("model", this.formData.model);
            fd.append("params", this.formData.params);
            fd.append("supname", this.formData.supname);
            fd.append("supid", this.formData.supid);
            fd.append("mmq", this.formData.mmq);
            fd.append("unit", this.formData.unit);
            fd.append("num", this.formData.num);
            fd.append("price", this.formData.price);
            fd.append("allregion", this.formData.allregion ? 1 : 0);
            fd.append("region", this.formData.region);
            fd.append("cklink", this.formData.cklink);
            fd.append("memo", this.formData.memo);
            fd.append("exptime", this.formData.exptime);

            let fid = 0;
            this.thumbuploadConfig.fileList.forEach(file => {
              if (file.raw) {
                fd.append("thumb_" + fid, file.raw);
                fid++;
              }
            });

            fid = 0;
            this.zzuploadConfig.fileList.forEach(file => {
              if (file.raw) {
                fd.append("zizhi_" + fid, file.raw);
                fid++;
              }
            });


            this.$axiosUploader.post("api/admin/productnew/create", fd).then(res => {
              if (res.status == 200 && res.data.code == 0) {
                this.$message({
                  message: "上架申请已提交!",
                  showClose: true,
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.dialogVisible = false;
                    this.$emit("closeHandler");
                  }
                });

                this.thumbuploadConfig.imgList = res.data.thumbs;
                this.zzuploadConfig.imgList = res.data.zizhi;

                this.thumbuploadConfig.fileList = [];
                this.thumbuploadConfig.removeids = [];
                this.zzuploadConfig.fileList = [];
                this.zzuploadConfig.removeids = [];
                this.$refs.thumbupload.clearFiles();
                this.$refs.zzupload.clearFiles();
              } else {
                this.$message.error({
                  message: res.data.msg,
                  duration: 1500,
                  showClose: true
                });
              }
            });

          }
        })
      }
    }
  }
</script>

<style>
  .title {
    position: relative;
    padding-left: 10px;
    margin-bottom: 15px;
    font-size: 14px;
    color: #333;
    font-weight: 700;
  }

  .title:before {
    content: "";
    position: absolute;
    top: 4px;
    left: 0;
    width: 5px;
    height: 65%;
    background-color: #249af3;
  }

  // 上传图片框样式
  .el-upload-list el-upload-list--picture-card {
    height: 96px !important;
    width: 96px !important;
    line-height: 96px !important;
  }

  .el-upload--picture-card {
    height: 96px !important;
    width: 96px !important;
    line-height: 96px !important;
  }

  .el-upload-list__item {
    height: 96px !important;
    width: 96px !important;
    line-height: 96px !important;
  }

  .el-upload-list__item-status-label i {
    position: absolute;
    width: 12x;
    right: 12px;
    top: 0px;
  }

  .el-upload--picture-card {
    height: 96px !important;
    width: 96px !important;
    line-height: 96px !important;
  }

  .el-upload-list__item {
    height: 96px !important;
    width: 96px !important;
    line-height: 96px !important;
    transition: none !important;
  }

  .el-upload-list__item-status-label i {
    position: absolute;
    width: 12x;
    right: 12px;
    top: 0px;
  }
</style>
